<template>
    <el-popover v-model="visible" placement="top-start" title="选择图标" width="566" trigger="click">
        <el-input
            v-model="name"
            style="position: relative"
            clearable
            placeholder="请输入图标名称"
            @clear="filterIcons"
            @input.native="filterIcons"
        >
            <i slot="suffix" class="el-icon-search el-input__icon" />
        </el-input>
        <ul class="icons">
            <li v-for="(item, index) in iconsArray" :key="index" class="icons-item" @click="emitIcon(item.font_class)">
                <svg class="icon svg-icon" aria-hidden="true">
                    <use :xlink:href="`#icon-${item.font_class}`"></use>
                </svg>
            </li>
        </ul>
        <el-input slot="reference" v-model="iconName" placeholder="请选择图标" readonly>
            <template slot="prepend">
                <svg class="icon svg-icon" aria-hidden="true">
                    <use :xlink:href="`#icon-${iconName}`"></use>
                </svg>
            </template>
        </el-input>
    </el-popover>
</template>
<script>
const iconfontObj = require('@/assets/iconfont/iconfont.json')
export default {
    model: {
        prop: 'iconName',
        event: 'icon-pick'
    },
    props: {
        iconName: {
            type: String,
            default: ''
        }
    },
    watch: {},
    data() {
        return {
            name: '',
            visible: false,
            iconsArray: iconfontObj.glyphs
        }
    },
    mounted() {
        this.iconsArray = iconfontObj.glyphs
    },
    methods: {
        filterIcons() {
            this.iconsArray = iconfontObj.glyphs
            if (this.name) {
                this.iconsArray = this.iconsArray.filter((item) => item.includes(this.name))
            }
        },
        emitIcon(icon) {
            this.$emit('icon-pick', icon)
            this.visible = false
        }
    }
}
</script>
<style lang="scss" scoped>
.icons {
    height: 300px;
    width: 100%;
    padding: 0;
    margin: 10px 0 0 0;
    overflow-y: scroll;
}
.icons-item {
    float: left;
    width: 20px;
    text-align: center;
    list-style: none;
    cursor: pointer;
    height: 20px;
    position: relative;
    padding: 10px;
    box-sizing: content-box;
    &:hover {
        background-color: #fef0f0;
    }
}
.svg-icon {
    width: 20px;
    height: 20px;
    vertical-align: middle;
}
</style>
